<template>
  <div class="van-cell">
    <van-field
      readonly
      clickable
      :value="date"
      :label="label"
      :rules="rules"
      placeholder="选择日期区间"
      @click="show = true"
    />
    <van-calendar
      type="range"
      :max-range="maxRange"
      :default-date="defaultDate"
      :allow-same-day="true"
      :max-date="maxDate"
      v-model="show"
      v-bind="$attrs"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
export default {
  props:{
    value:{
      type:[String]
    },
    label:{
      type:String,
      default:'日历'
    },
    maxRange:{
      type:[String,Number],
      default:null
    },
    maxDate:{
      type:[Date],
      default(){
        const cur = new Date();
        const year = cur.getFullYear();
        cur.setFullYear(year+1);
        return cur
      }
    },
    rules:{
      type:[Array],
      default(){
        return []
      }
    },
    separator:{
      type:[String],
      default:'-'
    },
    separatorRange:{
      type:[String],
      default:' - '
    },
  },
  data() {
    return {
      date: '',
      show: false,
      defaultDate:'',
    };
  },
  watch:{
    value:{
      immediate:true,
      handler(v){
        if(v){
          this.defaultDate=this.createDate();
          this.date = v
        }else{
          this.defaultDate=null;
        }
      }
    }
  },
  methods: {
    createDate(){
      const [start, end]= (this.value||'').split(this.separatorRange);
      const dateReg=new RegExp(`\\d{4}${this.separator}\\d{1,2}${this.separator}\\d{1,2}`);
      const createDate = s=>{
        const [year,month,day]=s.split(this.separator)
        return new Date(year,month-1,day)
      }
      if(start && end && dateReg.test(start) && dateReg.test(end)){
        return [createDate(start),createDate(end)]
      }
    },
    zero(n){
      return n<10?'0'+n:n+'';
    },
    formatDate(date) {
      return `${date.getFullYear()}${this.separator}${this.zero(date.getMonth() + 1)}${this.separator}${this.zero(date.getDate())}`;
    },
    onConfirm(date) {
      const [start, end] = date;
      this.show = false;
      this.date = `${this.formatDate(start)}${this.separatorRange}${this.formatDate(end)}`;
      this.$emit('input',this.date)
    },
  },
};
</script>

<style lang="less" scoped>
</style>